<!DOCTYPE html>
<html>
  <head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">
  <meta name="description" content="along&#39;s blog">
  <meta name="keyword" content="hexo-theme, vuejs">
  
    <link rel="shortcut icon" href="/css/images/logo.png">
  
  <title>
    
      vue3 响应式原理 | ALONG
    
  </title>
  <link href="/cdn.along/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
  <link href="/cdn.along/nprogress/0.2.0/nprogress.min.css" rel="stylesheet">
  <link href="/cdn.along/highlight.js/9.12.0/styles/tomorrow.min.css" rel="stylesheet">
  
<link rel="stylesheet" href="/css/style.css">

  
  <script src="/cdn.along/jquery/3.2.1/jquery.min.js"></script>
  <script src="/cdn.along/geopattern/1.2.3/js/geopattern.min.js"></script>
  <script src="/cdn.along/nprogress/0.2.0/nprogress.min.js"></script>
  
    
<script src="/js/qrious.js"></script>

  
  
  
  
    <!-- MathJax support START -->
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="/cdn.along/mathjax/2.7.5/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
    <!-- MathJax support END -->
  


  
  
    
<script src="/js/local-search.js"></script>


<meta name="generator" content="Hexo 5.4.0"></head>
<div class="wechat-share">
  <img src="/css/images/logo.png" />
</div>
  <body>
    <header class="header fixed-header">
  <div class="header-container">
    <a class="home-link" href="/">
      <div class="logo"></div>
      <span>ALONG</span>
    </a>
    <ul class="right-list">
      
        <li class="list-item">
          
            <a href="/" class="item-link">Home</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/tags/" class="item-link">Tags</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/archives/" class="item-link">Archives</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/about/" class="item-link">About</a>
          
        </li>
      
      
        <li class="menu-item menu-item-search right-list">
    <a role="button" class="popup-trigger">
        <i class="fa fa-search fa-fw"></i>
    </a>
</li>
      
    </ul>
    <div class="menu">
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </div>
    <div class="menu-mask">
      <ul class="menu-list">
        
          <li class="menu-item">
            
              <a href="/" class="menu-link">Home</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/tags/" class="menu-link">Tags</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/archives/" class="menu-link">Archives</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/about/" class="menu-link">About</a>
            
          </li>
        
      </ul>
    </div>
    
      <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
            <span class="search-icon">
                <i class="fa fa-search"></i>
            </span>
            <div class="search-input-container">
                <input autocomplete="off" autocapitalize="off"
                    placeholder="Please enter your keyword(s) to search." spellcheck="false"
                    type="search" class="search-input">
            </div>
            <span class="popup-btn-close">
                <i class="fa fa-times-circle"></i>
            </span>
        </div>
        <div id="search-result">
            <div id="no-result">
                <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
            </div>
        </div>
    </div>
</div>
    
  </div>
</header>

    <div id="article-banner">
  <h2>vue3 响应式原理</h2>
  <p class="post-date">2020-10-27</p>
  <div class="arrow-down">
    <a href="javascript:;"></a>
  </div>
</div>
<main class="app-body flex-box">
  <!-- Article START -->
  <article class="post-article">
    <section class="markdown-content"><h3 id="辅助函数"><a href="#辅助函数" class="headerlink" title="辅助函数"></a>辅助函数</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> isObject = <span class="function"><span class="params">val</span> =&gt;</span> val !== <span class="literal">null</span> &amp;&amp; <span class="keyword">typeof</span> val === <span class="string">&#x27;object&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 用于判断目标是否是对象，是对象进行代理</span></span><br><span class="line"><span class="keyword">const</span> convert = <span class="function"><span class="params">target</span> =&gt;</span> isObject(target) ? reactive(target) : target;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 判断对象本身是否有目标属性</span></span><br><span class="line"><span class="keyword">const</span> hasOwnProperty = <span class="built_in">Object</span>.prototype.hasOwnProperty</span><br><span class="line"><span class="keyword">const</span> hasOwn = <span class="function">(<span class="params">target, key</span>) =&gt;</span> hasOwnProperty.call(target, key);</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="reactive"><a href="#reactive" class="headerlink" title="reactive"></a>reactive</h3><ul>
<li>接收一个参数， 判断是否是对象</li>
<li>创建拦截器对象handler，设置get/set/deleteProperty<ul>
<li>get 中调用track收集依赖</li>
<li>set/deleteProperty 中调用trigger触发更新</li>
</ul>
</li>
<li>返回Proxy对象</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * reactive函数接收target参数，将其代理成响应式对象并返回响应式对象</span></span><br><span class="line"><span class="comment"> * reactive只能处理对象和数组，不能处理原始数据类型</span></span><br><span class="line"><span class="comment"> */</span> </span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">reactive</span> (<span class="params">target</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (!isObject(target)) <span class="keyword">return</span> target;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">const</span> handler = &#123;</span><br><span class="line">        get(target, key, receiver) &#123;</span><br><span class="line">            <span class="comment">// 收集依赖</span></span><br><span class="line">            track(target, key);</span><br><span class="line"></span><br><span class="line">            <span class="keyword">const</span> result = <span class="built_in">Reflect</span>.get(target, key, receiver)</span><br><span class="line">            <span class="comment">// 如果是对象，代理然后返回</span></span><br><span class="line">            <span class="comment">// 在访问的时候才会对深层的对象进行代理，惰性代理，提升性能</span></span><br><span class="line">            <span class="keyword">return</span> convert(result);</span><br><span class="line">        &#125;,</span><br><span class="line">        set(target, key, value, receiver) &#123;</span><br><span class="line">            <span class="keyword">const</span> oldValue = <span class="built_in">Reflect</span>.get(target, key, receiver);</span><br><span class="line">            <span class="comment">// 默认返回true，oldvalue等于value时返回true，但不触发更新</span></span><br><span class="line">            <span class="keyword">let</span> result = <span class="literal">true</span>;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">if</span> (oldValue !== value) &#123;</span><br><span class="line">                result = <span class="built_in">Reflect</span>.set(target, key, value, receiver);</span><br><span class="line"></span><br><span class="line">                <span class="comment">// 触发更新</span></span><br><span class="line">                trigger(target, key);</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">return</span> result;</span><br><span class="line">        &#125;,</span><br><span class="line">        deleteProperty(target, key) &#123;</span><br><span class="line">            <span class="keyword">const</span> haskey = hasOwn(target, key);</span><br><span class="line">            <span class="keyword">const</span> result = <span class="built_in">Reflect</span>.deleteProperty(target, key);</span><br><span class="line">            <span class="keyword">if</span> (haskey &amp;&amp; result) &#123;</span><br><span class="line">                <span class="comment">// 触发更新</span></span><br><span class="line">                trigger(target, key);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">return</span> result;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Proxy</span>(target, handler);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="effect"><a href="#effect" class="headerlink" title="effect"></a>effect</h3><ul>
<li>effect函数接收一个函数</li>
<li>effect首先在全局缓存接收到的参数callback</li>
<li>执行callback函数，在这个函数中由于读取了响应式数据，会触发handler中get中的track函数，收集依赖</li>
<li>依赖收集完成后，清除全局缓存的callback引用</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * effect函数接收一个函数，这个函数会在第一次和依赖的响应式对象发生变化时执行</span></span><br><span class="line"><span class="comment"> */</span> </span><br><span class="line"><span class="keyword">let</span> activeEffect = <span class="literal">null</span>;</span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">effect</span>(<span class="params">callback</span>) </span>&#123;</span><br><span class="line">    activeEffect = callback;</span><br><span class="line">    callback(); <span class="comment">// callback会收集响应式对象属性，此时可以来收集依赖</span></span><br><span class="line">    activeEffect = <span class="literal">null</span>;</span><br><span class="line">&#125; </span><br></pre></td></tr></table></figure>

<h3 id="track"><a href="#track" class="headerlink" title="track"></a>track</h3><ul>
<li>track 函数用于收集依赖，接收响应式对象和属性名</li>
<li>在上方的effect中，在全局缓存了一个activeEffect,方便track能访问，当执行到callback()时，会访问相应对象的属性，相应对象handler方法的get方法中会首先调用track收集依赖。track方法只在activeEffect有值时继续执行，所以在effect调用时访问响应式属性才会真正进入track方法收集依赖。也就是effect方法调用时的回调函数第一次执行时才会收集依赖</li>
<li>track函数外部会声明一个targetMap,用于保存响应式对象的所有被依赖属性和回调函数的集合。targetMap 结构实例  {target:{key1: <a href="Set">cb1, cb2</a>, key2: <a href="Set">cb</a>}(Map)}(WeakMap)</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * track 函数用于收集依赖</span></span><br><span class="line"><span class="comment"> * 在上方的effect中，在全局缓存了一个activeEffect,方便track能访问</span></span><br><span class="line"><span class="comment"> * 当执行到callback()时，会访问相应对象的属性，相应对象handler方法的get方法中会首先调用track收集依赖。</span></span><br><span class="line"><span class="comment"> * track方法只在activeEffect有值时继续执行，所以在effect调用时访问响应式属性才会真正进入track方法收集依赖。也就是effect方法调用时的回调函数第一次执行时才会收集依赖</span></span><br><span class="line"><span class="comment"> * track函数外部会声明一个targetMap,用户保存响应式对象的所有被依赖属性和回调函数的集合。targetMap 结构实例  &#123;target:&#123;key1: [cb1, cb2](Set), key2: [cb](Set)&#125;(Map)&#125;(WeakMap)</span></span><br><span class="line"><span class="comment"> */</span> </span><br><span class="line"><span class="keyword">let</span> targetMap = <span class="keyword">new</span> <span class="built_in">WeakMap</span>();</span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">track</span>(<span class="params">target, key</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (!activeEffect) <span class="keyword">return</span>;</span><br><span class="line">    <span class="keyword">let</span> depsMap = targetMap.get(target);</span><br><span class="line">    <span class="keyword">if</span> (!depsMap) &#123;</span><br><span class="line">        targetMap.set(target, (depsMap = <span class="keyword">new</span> <span class="built_in">Map</span>()))</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">let</span> dep = depsMap.get(key);</span><br><span class="line">    <span class="keyword">if</span> (!dep) &#123;</span><br><span class="line">        depsMap.set(key, (dep = <span class="keyword">new</span> <span class="built_in">Set</span>()))</span><br><span class="line">    &#125;</span><br><span class="line">    dep.add(activeEffect);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="trigger"><a href="#trigger" class="headerlink" title="trigger"></a>trigger</h3><ul>
<li>trigger函数用于触发更新，接收响应式对象和属性名</li>
<li>通过响应式对象和属性名从targetMap取出所有的回调函数。依次执行处罚更新</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * trigger函数用于触发更新,查找这个属性是否有对应的回调函数</span></span><br><span class="line"><span class="comment"> */</span> </span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">trigger</span>(<span class="params">target, key</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> depsMap = targetMap.get(target);</span><br><span class="line">    <span class="keyword">if</span> (!depsMap) <span class="keyword">return</span>;</span><br><span class="line">    <span class="keyword">const</span> dep = depsMap.get(key);</span><br><span class="line">    <span class="keyword">if</span> (dep) &#123;</span><br><span class="line">        dep.forEach(<span class="function"><span class="params">effect</span> =&gt;</span> &#123;</span><br><span class="line">            effect()</span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="ref"><a href="#ref" class="headerlink" title="ref"></a>ref</h3><ul>
<li>ref 用于将一个变量处理成响应式，可以用于处理基础数据类型或者对象</li>
<li>返回一个带有__v_isRef标识的对象，并将参数处理成响应式（如果是基本数据类型直接保存到value中）保存到返回对象的value中，value通过getter/setter拦截。</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * ref 用于将一个变量处理成响应式，可以用于处理基础数据类型或者对象</span></span><br><span class="line"><span class="comment"> * 最终返回一个对象r，如果r的value在effct中被访问，会注册依赖</span></span><br><span class="line"><span class="comment"> * 同样，r的value被修改时，也会触发回调</span></span><br><span class="line"><span class="comment"> * </span></span><br><span class="line"><span class="comment"> * ref可以把基本数据类型数据转换成响应式数据，可以通过value属性访问，模板中使用可以省略.value</span></span><br><span class="line"><span class="comment"> * ref返回的对象，重新复制成对象也是响应式的</span></span><br><span class="line"><span class="comment"> * reactive返回的的对象，重新复制丢失响应式</span></span><br><span class="line"><span class="comment"> * reactive返回的对象不可以解构</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">ref</span>(<span class="params">raw</span>) </span>&#123;</span><br><span class="line">    <span class="comment">// 判断是否是ref创建的对象，是直接返回</span></span><br><span class="line">    <span class="keyword">if</span> (isObject(raw) &amp;&amp; raw.__v_isRef) <span class="keyword">return</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 判断是否是对象，是的话转换成响应式对象，否则返回raw</span></span><br><span class="line">    <span class="keyword">let</span> value = convert(raw);</span><br><span class="line">    <span class="keyword">const</span> r = &#123;</span><br><span class="line">        __v_isRef: <span class="literal">true</span>,</span><br><span class="line">        <span class="keyword">get</span> <span class="title">value</span>() &#123;</span><br><span class="line">            track(r, <span class="string">&#x27;value&#x27;</span>);</span><br><span class="line">            <span class="keyword">return</span> value;</span><br><span class="line">        &#125;,</span><br><span class="line">        <span class="keyword">set</span> <span class="title">value</span>(<span class="params">newValue</span>) &#123;</span><br><span class="line">            <span class="keyword">if</span> (newValue !== value) &#123;</span><br><span class="line">                raw = newValue;</span><br><span class="line">                value = convert(raw);</span><br><span class="line">                trigger(r, <span class="string">&#x27;value&#x27;</span>)</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> r;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="toRefs"><a href="#toRefs" class="headerlink" title="toRefs"></a>toRefs</h3><ul>
<li>toRefs 接收一个 reactive返回的响应式对象，将该对象的所有属性通过ref函数处理返回，并返回一个包装对象</li>
<li>通过这种方式返回的对象，解构之后仍然是响应式</li>
<li>其实就是利用了结构赋值时引用传递的原理</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * toRefs 接收一个 reactive返回的响应式对象，将该对象的所有属性处理成ref</span></span><br><span class="line"><span class="comment"> * 返回的格式（将值包装到value中），并返回一个包装对象，</span></span><br><span class="line"><span class="comment"> * 通过这种方式返回的对象，解构之后仍然是响应式</span></span><br><span class="line"><span class="comment"> * 其实就是利用了赋值时引用传递的原理</span></span><br><span class="line"><span class="comment"> */</span> </span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">toRefs</span>(<span class="params">proxy</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> ret = proxy <span class="keyword">instanceof</span> <span class="built_in">Array</span> ? <span class="keyword">new</span> <span class="built_in">Array</span>(proxy.length) : &#123;&#125;;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">const</span> key <span class="keyword">in</span> proxy) &#123;</span><br><span class="line">        ret[key] = toProxyRef(proxy, key);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> ret;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// toRefs 内部调用的函数，用于将一个响应式的属性值处理成响应式</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">toProxyRef</span> (<span class="params">proxy, key</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> r = &#123;</span><br><span class="line">        __v_isRef: <span class="literal">true</span>,</span><br><span class="line">        <span class="keyword">get</span> <span class="title">value</span>() &#123;</span><br><span class="line">            <span class="keyword">return</span> proxy[key];</span><br><span class="line">        &#125;,</span><br><span class="line">        <span class="keyword">set</span> <span class="title">value</span>(<span class="params">newValue</span>) &#123;</span><br><span class="line">            proxy[key] = newValue</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> r;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="computed"><a href="#computed" class="headerlink" title="computed"></a>computed</h3><ul>
<li>computed 是effect包装，接收一个函数getter， 返回一个响应式的对象（计算属性）</li>
<li>内部调用effect，收集依赖，当依赖的响应式对象改变时，会触发getter修改返回的响应式对象的值</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * computed 是effect包装，返回一个响应式的对象（计算属性）</span></span><br><span class="line"><span class="comment"> * 当依赖数据改变时，会修改返回的响应式对象的值</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">computed</span> (<span class="params">getter</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> result = ref(); <span class="comment">// 创建一个空的ref，不在effectn内部创建为了保持对象是同一引用</span></span><br><span class="line"></span><br><span class="line">    effect(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">        result.value = getter();</span><br><span class="line">    &#125;)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> result;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</section>
    <!-- Tags START -->
    
      <div class="tags">
        <span>Tags:</span>
        
  <a href="/tags#vue" >
    <span class="tag-code">vue</span>
  </a>

  <a href="/tags#vue源码" >
    <span class="tag-code">vue源码</span>
  </a>

  <a href="/tags#vue3" >
    <span class="tag-code">vue3</span>
  </a>

      </div>
    
    <!-- Tags END -->
    <!-- NAV START -->
    
  <div class="nav-container">
    <!-- reverse left and right to put prev and next in a more logic postition -->
    
      <a class="nav-left" href="/2020/10/23/%E5%8E%9F%E5%9E%8B%E9%93%BE%E7%BB%A7%E6%89%BF/">
        <span class="nav-arrow">← </span>
        
          原型链继承
        
      </a>
    
    
      <a class="nav-right" href="/2020/10/29/vue%E5%85%A8%E5%AE%B6%E6%A1%B6-ts-eslint%E9%A1%B9%E7%9B%AE%E6%90%AD%E5%BB%BA/">
        
          vue全家桶+ts+eslint项目搭建
        
        <span class="nav-arrow"> →</span>
      </a>
    
  </div>

    <!-- NAV END -->
    <!-- 打赏 START -->
    
      <div class="money-like">
        <div class="reward-btn">
          赏
          <span class="money-code">
            <span class="alipay-code">
              <div class="code-image"></div>
              <b>使用支付宝打赏</b>
            </span>
            <span class="wechat-code">
              <div class="code-image"></div>
              <b>使用微信打赏</b>
            </span>
          </span>
        </div>
        <p class="notice">若你觉得我的文章对你有帮助，欢迎点击上方按钮对我打赏</p>
      </div>
    
    <!-- 打赏 END -->
    <!-- 二维码 START -->
    
      <div class="qrcode">
        <canvas id="share-qrcode"></canvas>
        <p class="notice">扫描二维码，分享此文章</p>
      </div>
    
    <!-- 二维码 END -->
    
      <!-- No Comment -->
    
  </article>
  <!-- Article END -->
  <!-- Catalog START -->
  
    <aside class="catalog-container">
  <div class="toc-main">
    <strong class="toc-title">Catalog</strong>
    
      <ol class="toc-nav"><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#%E8%BE%85%E5%8A%A9%E5%87%BD%E6%95%B0"><span class="toc-nav-text">辅助函数</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#reactive"><span class="toc-nav-text">reactive</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#effect"><span class="toc-nav-text">effect</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#track"><span class="toc-nav-text">track</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#trigger"><span class="toc-nav-text">trigger</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#ref"><span class="toc-nav-text">ref</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#toRefs"><span class="toc-nav-text">toRefs</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#computed"><span class="toc-nav-text">computed</span></a></li></ol>
    
  </div>
</aside>
  
  <!-- Catalog END -->
</main>

<script>
  (function () {
    var url = 'https://github.com/alongithub/2020/10/27/vue3-响应式原理/';
    var banner = ''
    if (banner !== '' && banner !== 'undefined' && banner !== 'null') {
      $('#article-banner').css({
        'background-image': 'url(' + banner + ')'
      })
    } else {
      $('#article-banner').geopattern(url)
    }
    $('.header').removeClass('fixed-header')

    // error image
    $(".markdown-content img").on('error', function() {
      $(this).attr('src', '/css/images/error_icon.png')
      $(this).css({
        'cursor': 'default'
      })
    })

    // zoom image
    $(".markdown-content img").on('click', function() {
      var src = $(this).attr('src')
      if (src !== '/css/images/error_icon.png') {
        var imageW = $(this).width()
        var imageH = $(this).height()

        var zoom = ($(window).width() * 0.95 / imageW).toFixed(2)
        zoom = zoom < 1 ? 1 : zoom
        zoom = zoom > 2 ? 2 : zoom
        var transY = (($(window).height() - imageH) / 2).toFixed(2)

        $('body').append('<div class="image-view-wrap"><div class="image-view-inner"><img src="'+ src +'" /></div></div>')
        $('.image-view-wrap').addClass('wrap-active')
        $('.image-view-wrap img').css({
          'width': `${imageW}`,
          'transform': `translate3d(0, ${transY}px, 0) scale3d(${zoom}, ${zoom}, 1)`
        })
        $('html').css('overflow', 'hidden')

        $('.image-view-wrap').on('click', function() {
          $(this).remove()
          $('html').attr('style', '')
        })
      }
    })
  })();
</script>


  <script>
    var qr = new QRious({
      element: document.getElementById('share-qrcode'),
      value: document.location.href
    });
  </script>






    <div class="scroll-top">
  <span class="arrow-icon"></span>
</div>
    <footer class="app-footer">
  <p class="copyright">
    Copyright&copy; 2019-2022 along
    <br>
    <a href="https://beian.miit.gov.cn/" target="_blank">京ICP备2020044791号-1</a>
    <!-- <br>
    Theme by <a href="https://github.com/alongithub">alongithub</a>
     -->
  </p>
</footer>

<script>
  function async(u, c) {
    var d = document, t = 'script',
      o = d.createElement(t),
      s = d.getElementsByTagName(t)[0];
    o.src = u;
    if (c) { o.addEventListener('load', function (e) { c(null, e); }, false); }
    s.parentNode.insertBefore(o, s);
  }
</script>
<script>
  async("/cdn.along/fastclick/1.0.6/fastclick.min.js", function(){
    FastClick.attach(document.body);
  })
</script>

<script>
  var hasLine = 'true';
  async("/cdn.along/highlight.js/9.12.0/highlight.min.js", function(){
    $('figure pre').each(function(i, block) {
      var figure = $(this).parents('figure');
      if (hasLine === 'false') {
        figure.find('.gutter').hide();
      }
      hljs.configure({useBR: true});
      var lang = figure.attr('class').split(' ')[1] || 'code';
      var codeHtml = $(this).html();
      var codeTag = document.createElement('code');
      codeTag.className = lang;
      codeTag.innerHTML = codeHtml;
      $(this).attr('class', '').empty().html(codeTag);
      figure.attr('data-lang', lang.toUpperCase());
      hljs.highlightBlock(block);
    });
  })
</script>
<!-- Baidu Tongji -->


<script src="/js/script.js"></script>


  </body>
</html>